'''
Created on May 19, 2011

@author: elia
'''

from django.contrib.auth.models import User
import re

# remember repository. for deployment
from core.models import Collection, Course, Tag

# http://bradmontgomery.blogspot.com/2009/04/restricting-access-by-group-in-django.html

def is_student(groups):
    return groups.filter(name = 'Students').count() == 1

def is_teacher(groups):
    return groups.filter(name = 'Teachers').count() == 1

def getUser(session):
    result = User.objects.filter(id = session.get('_auth_user_id'))
    try:
        return result[0]
    except Exception:
        return None

def getUserRole(user):
    if is_teacher(user.groups):
        return 'teacher'
    else:
        return 'student'

def getCollection(id):
    result = Collection.objects.filter(id = id)
    try:
        return result[0]
    except Exception:
        return None
    
def getCourse(id):
    result = Course.objects.filter(id = id)
    try:
        return result[0]
    except Exception:
        return None
    
def getTag(name):
    result = Tag.objects.filter(name = name)
    try:
        return result[0]
    except Exception:
        return None

"""
    Check file media type
    return a tuple (mediaType, fileExtension) otherwise None (mediaType Unknown)
    
"""
def getMediaType(fileName):
    type = None
    
    regexJPG = re.compile('\.jpg$|\.JPG$|\.jpeg$|\.JPEG$');
    regexTXT = re.compile('\.txt$|\.TXT$');
    regexOGG = re.compile('\.ogg$|\.OGG$');
    regexOGV = re.compile('\.ogv$|\.OGV$');
    regexMP3 = re.compile('\.mp3$|\.MP3$');
    
    if regexJPG.search(fileName):
        type = ('image/jpeg', 'jpg')
    elif regexTXT.search(fileName):
        type = ('text/plain', 'txt')
    elif regexOGG.search(fileName):
        type = ('audio/ogg', 'ogg')
    elif regexOGV.search(fileName):
        type = ('video/ogg', 'ogv')
    elif regexMP3.search(fileName):
        type = ('audio/mpeg', 'mp3')
    
    return type